﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.CompilerServices;

namespace svnbox {
    internal enum LogSource {
        SVN,MONITOR,GUI
    }  

    internal class AppLog {
        static FileStream LogStream;
        static StreamWriter Log;
        static string LogFilePath;
        internal static bool EnableLogging = true;
        static string EncodeXmlString(object src) {
            if (src == null) return "null";
            return src.ToString().Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;");            
        }
        [MethodImpl(MethodImplOptions.Synchronized)]
        internal static void Write(LogSource Source,Exception Ex) {
            if (Ex == null || !EnableLogging) return;
            if (Ex.InnerException != null) Ex = Ex.InnerException;

            try {
                if (!Directory.Exists(App.LogExceptionLocation))
                    Directory.CreateDirectory(App.LogExceptionLocation);
                LogFilePath =  Path.Combine(
                    Path.GetDirectoryName(App.LogExceptionLocation)
                    , DateTime.Now.ToString("yyyy-MM-dd") + "." 
                    + Path.GetFileName(App.LogExceptionLocation));
                //LogFilePath = App.LogPath + "\\" + DateTime.Today.ToString("yyyy-MM-dd") + ".exception.log";
                LogStream = new FileStream(LogFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
                Log = new StreamWriter(LogStream, Encoding.UTF8);
                StringBuilder SB = new StringBuilder();
                if (LogStream.Length < 21)
                    SB.AppendLine("<ERRORLOG>");
                else
                    LogStream.Position = LogStream.Length - 13;
                SB.AppendLine("  <LOG TIME=\"{0}\" SOURCE=\"{1}\">");
                SB.AppendLine("    <EXCEPTION>{2}</EXCEPTION>");
                SB.AppendLine("    <MESSAGE>{3}</MESSAGE>");
                SB.AppendLine("    <SOURCE>{4}</SOURCE>");
                SB.AppendLine("    <STACK>{5}</STACK>");
                SB.AppendLine("  </LOG>");
                SB.AppendLine("</ERRORLOG>"); // End the xml file


                Log.Write( String.Format(SB.ToString(),
                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),//{0}
                    Source.ToString(),//{1}
                    EncodeXmlString(Ex), //{2}
                    EncodeXmlString(Ex.Message),//{3}
                    EncodeXmlString(Ex.Source),//{4}
                    EncodeXmlString(Ex.StackTrace)//{5}
                  ) ) ;


                SB = null;
            } catch{ } finally {
                if (Log != null) Log.Close(); Log = null;
                if (LogStream != null) LogStream.Close(); LogStream = null;
            }
        }
    }
}
